package org.bozo.im.service.protocols.xmpp.stanza.processor.sasl;

import java.io.IOException;
import java.util.StringTokenizer;

import org.bozo.im.service.protocols.xmpp.XMPPSession;
import org.bozo.im.service.protocols.xmpp.stanza.Stanza;
import org.bozo.im.service.protocols.xmpp.stanza.processor.StanzaProcessor;
import org.bozo.im.service.protocols.xmpp.stanza.task.sasl.MD5ChallengeTask;
import org.bozo.im.service.protocols.xmpp.util.encoding.Base64;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

public class ChallengeStanzaProcessor extends StanzaProcessor {

	private static ChallengeStanzaProcessor mInstance;

	private ChallengeStanzaProcessor() {}

	public static ChallengeStanzaProcessor getInstance() {
		if (mInstance == null)
			mInstance = new ChallengeStanzaProcessor();
		return mInstance;
	}

	@Override
	public Stanza getStanza() {
		return Stanza.SASL_CHALLENGE;
	}

	@Override
	public void processStanza(XmlPullParser pParser, XMPPSession pSession, StanzaProcessor pParentProcessor) throws XmlPullParserException, IOException {

		String lChallenge = pParser.nextText();
		String lDecodedChallenge = Base64.decode(lChallenge);

		String lRealm = null;
		String lNonce = null;
		String lQop = null;

		StringTokenizer lMain = new StringTokenizer(lDecodedChallenge, ",");

		while (lMain.hasMoreTokens()) {
			String lToken = lMain.nextToken();
			int lIndex = lToken.indexOf('=');
			String lKey = lToken.substring(0, lIndex);
			
			if (lKey.equals("realm")) {
				lRealm = lToken.substring(lIndex + 2, lToken.length() - 1);
			} else if (lKey.equals("nonce")) {
				lNonce = lToken.substring(lIndex + 2, lToken.length() - 1);
			} else if (lKey.equals("qop")) {
				lQop = lToken.substring(lIndex + 2, lToken.length() - 1);
			}
		}

		pSession.getTaskProcessor().pushTask(new MD5ChallengeTask("0", lRealm, lNonce, lQop));
	}
}
